package com.example.music_mediaplayer.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.duyin.quickscan.QuickScanManager;
import com.duyin.quickscan.baen.ScanResult;
import com.example.music_mediaplayer.R;
import com.example.music_mediaplayer.adapter.MyListViewAdapter;
import com.example.music_mediaplayer.globalvariable.GlobalVariable;
import com.example.music_mediaplayer.model.SongsInfomation;
import com.example.music_mediaplayer.service.MyService;
import com.example.music_mediaplayer.tool.HanziToPinyin;
import com.example.music_mediaplayer.tool.LogoutT;
import com.example.music_mediaplayer.tool.PermisionUtils;
import com.example.music_mediaplayer.tool.ToastTools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class LocationFragment extends Fragment{
    private View rootView;
    private ListView listView;
    public static MyListViewAdapter adapter;
    private Intent intent;
    private boolean flg = true;
    private List<Map<String ,String>> songLrcList  = new ArrayList<>();
    private File file;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null){
            rootView = inflater.inflate(R.layout.fragment_location,null);
        }
        initView(rootView);
        return rootView;
    }



    public void initView(View rootView){
        PermisionUtils.verifyStoragePermissions(getActivity());
        if (GlobalVariable.LocationSongList.size() == 0){
            getLocationSongList();
            scanSongLrc();
        }
        sortSongList();
        listView = (ListView) rootView.findViewById(R.id.song_list);
        adapter = new MyListViewAdapter(getActivity(), GlobalVariable.LocationSongList,1);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                intent = new Intent(getActivity(), MyService.class);
                intent.putExtra("url",GlobalVariable.LocationSongList.get(position).getSongPath());
                intent.putExtra("songName",GlobalVariable.LocationSongList.get(position).getSongName());
                intent.putExtra("songArtist",GlobalVariable.LocationSongList.get(position).getSongArtist());
                intent.putExtra("songPhoto","");
                intent.putExtra("songLrc",GlobalVariable.LocationSongList.get(position).getSongLyric());
                intent.putExtra("msg","");
                getActivity().startService(intent);
//                if (GlobalVariable.LieBiaoSongList.size()==0){
//                    GlobalVariable.LieBiaoSongList.add(GlobalVariable.LocationSongList.get(position));
//                }else{
//                    for (int j = 0;j<GlobalVariable.LieBiaoSongList.size();j++){
//                        if (GlobalVariable.LieBiaoSongList.get(j).getSongPath().equals(GlobalVariable.LocationSongList.get(position).getSongPath())){
//                            flg = true;
//                            return;
//                        }else{
//                            flg = false;
//                        }
//                    }
//                    if (flg == false){
//                        GlobalVariable.LieBiaoSongList.add(GlobalVariable.LocationSongList.get(position));
//                    }
//                }
            }
        });
    }

    /**
     * 歌曲与进行歌词匹配
     */
    public void setLrcInSongList(){
        for (int i = 0 ; i<GlobalVariable.LocationSongList.size() ; i++){
            for (int j = 0 ; j<songLrcList.size() ; j++){
                String[] s = songLrcList.get(j).get("songName").replace(" - ","_").split("_");
                Log.i("ccccccc",songLrcList.get(j).get("songLrcPath"));
                if (GlobalVariable.LocationSongList.get(i).getSongName().equals(s[0])){
                    String lrc = getStringSongLrcLocal(songLrcList.get(j).get("songLrcPath"));
                    LogoutT.logout( lrc+"lrc");
                    GlobalVariable.LocationSongList.get(i).setSongLyric(lrc);
                }
            }
        }
    }


    /**
     * 从指定文件夹中获取音乐资源
     */
    public void getSongOnFile(){
        //得到song文件夹的路径，File.separator(/)
        String filePath = Environment.getExternalStorageDirectory().getPath()+File.separator + "youlisten/music";
        //得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();
        //将所有的文件存入GlobalVariable.LocationSongList中，并过滤所有图片格式的文件
        for(int i = 0;i<files.length;i++){
            File file = files[i];
            if (checkIsSongFile(file.getPath())){
                String[] fs = file.getPath().split("/");
                String[] ns = fs[6].split(" - ");
                SongsInfomation songsInfomation = new SongsInfomation();
                songsInfomation.setSongPath(file.getPath());
                songsInfomation.setSongName(ns[0]);
                songsInfomation.setSongArtist(ns[1].substring(0 , ns[1].indexOf(".")));
                GlobalVariable.LocationSongList.add(songsInfomation);
                LogoutT.logout(GlobalVariable.LocationSongList.get(0).getSongPath()+"  aaa aa ");
            }
        }
    }

    public void sortSongList(){
        if (GlobalVariable.LocationSongList.size()!=0){
            for (SongsInfomation s : GlobalVariable.LocationSongList){
                s.setInitial(getLetter(s.getSongName()));
            }
        }
        sort();
    }


    /**
     * 排序方法
     */
    public void sort(){
        Collections.sort(GlobalVariable.LocationSongList, new Comparator<SongsInfomation>() {
            @Override
            public int compare(SongsInfomation o1, SongsInfomation o2) {
                if (o1.getInitial().equals(o2.getInitial())){
                    return o1.getSongName().compareTo(o2.getSongName());
                }else{
                    if ("#".equals(o1.getInitial())){
                        return 1;
                    }else if ("#".equals(o2.getInitial())){
                        return -1;
                    }
                    return o1.getInitial().compareTo(o2.getInitial());
                }
            }
        });
    }

    /**
     * 根据字符串获取当前首字母
     * @param name
     * @return
     */
    public String getLetter(String name){
        String DefaultLetter = "#";
        if (TextUtils.isEmpty(name)){
            return DefaultLetter;
        }
        char initial = name.toLowerCase().charAt(0);
        if (Character.isDigit(initial)){
            return DefaultLetter;
        }
        ArrayList<HanziToPinyin.Token> l = HanziToPinyin.getInstance().get(name.substring(0,1));
        if (l != null && l.size()>0 && l.get(0).target.length()>0){
            HanziToPinyin.Token token = l.get(0);
            //toLowerCase返回小写，toUpperCase()返回大写
            String letter = token.target.substring(0,1).toLowerCase();
            char c = letter.charAt(0);
            //这里的'a'和'z'要和letter的大小写保持一直。
            if (c<'a'||c>'z'){
                return DefaultLetter;
            }
            return letter;
        }
        return DefaultLetter;
    }

    /**
     * 检查扩展名，得到音乐格式的文件
     * @param fName
     * @return
     */
    @SuppressLint("DefaultLocale")
    public boolean checkIsSongFile(String fName){
        boolean isSongFile = false;
        //获取扩展名
        String fileEnd = fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
        if (fileEnd.equals("mp3")||fileEnd.equals("wav")||fileEnd.equals("mid")||fileEnd.equals("asf")||fileEnd.equals("mpg")||fileEnd.equals("avi")||fileEnd.equals("tti")){
            isSongFile = true;
        }else {
            isSongFile = false;
        }
        return isSongFile;
    }

    /**
     * 获取本地音乐列表
     */
    public void getLocationSongList(){
        /**
         * 查询媒体数据库
         * 参数分别为（路径，要查询的列名，条件语句，条件参数，排序）
         */
        LogoutT.logout("333333333");
        Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        //遍历媒体数据库
        if (cursor.moveToFirst()){
            while (!cursor.isAfterLast()){
                //歌曲编号
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
//                LogoutT.logout(id+"   id");
                //歌曲标题
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
//                LogoutT.logout(title+"   title");
                //歌曲的歌手名
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
//                LogoutT.logout(artist+"   artist");
                //歌曲文件路径
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
//                LogoutT.logout(url+"   url");
                //歌曲的总播放时长
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
//                LogoutT.logout(duration+"   duration");
                //歌曲文件的大小
                Long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

                if (size > 1024 * 800){//大于800K
                    SongsInfomation songsInfomation = new SongsInfomation();
                    songsInfomation.setSongArtist(artist);
                    songsInfomation.setSongName(title);
                    songsInfomation.setSongPath(url);
                    songsInfomation.setDuration(duration);
                    GlobalVariable.LocationSongList.add(songsInfomation);
               }
                cursor.moveToNext();
            }
        }
        file = new File(Environment.getExternalStorageDirectory().getPath()+File.separator + "youlisten/music");
        if (file.exists()){
            getSongOnFile();
        }
    }


    /**
     * 扫描手机歌词lrc
     */
    public void scanSongLrc(){
        QuickScanManager.getQuickScanManager().Init(getActivity()).getAllResult(".lrc", new QuickScanManager.OnResultListener() {
            @Override
            public void ScanSuccess(List<ScanResult> list) {
                songLrcList.clear();
                for (ScanResult scanResult : list){
                    Map<String ,String > map = new HashMap<String, String>();
                    map.put("songName",scanResult.getName());
                    map.put("songLrcPath",scanResult.getPath());
                    Log.i("787878",scanResult.getName());
                    songLrcList.add(map);
                }
                setLrcInSongList();
            }
            @Override
            public void ScanError(String msg) {
                ToastTools.toastMsg(getActivity(),"没有歌词");
            }
        });
    }

    /**
     * 本地读取歌词文件
     * @param path
     * @return
     */
    public String  getStringSongLrcLocal(String path){
        try {
            InputStream in =new FileInputStream(new File(path));
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len = in.read(buffer)) != -1){
                os.write(buffer , 0 ,len);
            }
            return os.toString("utf-8");  //文件编码是utf-8
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
